package com.xxhui.bezierdemo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by hui on 2016/7/7.
 */
public class SecondOrder extends View {

    private Paint paint ;
    private int centerX,centerY ;
    private PointF start , end , control;
    private Path path;


    public SecondOrder(Context context, AttributeSet attrs) {
        super(context, attrs);
        initSourse();
    }

    public SecondOrder(Context context) {
        super(context);
        initSourse();
    }

    private void initSourse(){
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(8);
        paint.setStyle(Paint.Style.STROKE);
        paint.setTextSize(60);

        start = new PointF(0,0);
        end = new PointF(0,0);
        control = new PointF(0,0);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        centerX = w/2;
        centerY = h/2;

        start.x = centerX-200;
        start.y = centerY;
        end.x = centerX+200;
        end.y = centerY ;
        control.x = centerX;
        control.y = centerY-100;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        control.x = event.getX();
        control.y = event.getY();
        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //canvas.translate(centerX , centerY);
        drawPointF(canvas);
        drawLine(canvas);
        drawBezier(canvas);
    }

    private void drawPointF(Canvas canvas){
        paint.setColor(Color.GRAY);
        paint.setStrokeWidth(20);
        canvas.drawPoint(start.x , start.y , paint);
        canvas.drawPoint(end.x , end.y , paint);
        canvas.drawPoint(control.x , control.y , paint);
    }

    private void drawLine(Canvas canvas){
        paint.setStrokeWidth(4);
        canvas.drawLine(start.x , start.y , control.x , control.y , paint);
        canvas.drawLine(control.x , control.y , end.x , end.y  ,paint);
    }

    private void drawBezier(Canvas canvas){
        paint.setColor(Color.RED);
        paint.setStrokeWidth(8);

        path = new Path();
        path.moveTo(start.x , start.y);
        path.quadTo(control.x , control.y , end.x , end.y);

        canvas.drawPath(path , paint);
    }
}
